package club.hicode.daydayup.ssh;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.jcabi.ssh.Shell;
import com.jcabi.ssh.SshByPassword;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

/**
 * 测试1
 *
 * @author Liu Chunfu
 * @date 2018-07-24 上午10:18
 **/
public class SSHTest2 {

    @Test
    public void test1() throws Exception {
        SSHUtils ssh = new SSHUtils("alios", "root", "j279PCdU$^Tm");
        String s = ssh.runShell("whoami", CharsetUtil.UTF_8);
        System.out.println(s);
    }

    @Test
    public void test2() throws Exception {
        String s = exeCommand("alios", 22, "root", "j279PCdU$^Tm", "whoami");
        System.out.println(s);
    }

    @Test
    public void test3() throws Exception {
        String s = exeCommand("alios", 22, "root", "j279PCdU$^Tm", "echo ilove you");
        System.out.println(s);
    }


    public static String exeCommand(String host, int port, String user, String password, String command)
            throws JSchException, IOException {

        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, port);
        session.setConfig("StrictHostKeyChecking", "no");
        //    java.util.Properties config = new java.util.Properties();
        //   config.put("StrictHostKeyChecking", "no");

        session.setPassword(password);
        session.connect();

        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        InputStream in = channelExec.getInputStream();
        channelExec.setCommand(command);
        channelExec.setErrStream(System.err);
        channelExec.connect();
        String out = IoUtil.read(in, "UTF-8");
        //String out = StrUtil.str(in, "UTF-8");

        channelExec.disconnect();
        session.disconnect();

        return out;
    }
}
